package com.ruoyi.robot.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ruoyi.robot.pojo.po.Customer;

import java.util.Calendar;

/**
 * @author admin
 */
public class JWTUtils {

    private static final String SIGN="abcdefg1234567";

    /**
     * 获取token
     * @param u user
     * @return token
     */
    public static String getToken(Customer u) {
        Calendar instance = Calendar.getInstance();
        //默认令牌过期时间7天
        instance.add(Calendar.DATE, 7);

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("customerAccount", u.getCustomerAccount())
                .withClaim("customerName",u.getCustomerName())
                .withClaim("customerPhone",u.getCustomerPhone())
                .withClaim("customerEmail",u.getCustomerEmail())
                .withClaim("avatar",u.getAvatar())
                .withClaim("customerId",String.valueOf(u.getCustomerId()));

        return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGN));
    }

    /**
     * 验证token合法性 成功返回token
     */
    public static DecodedJWT verify(String token){
        //获取登录用户真正的密码假如数据库查出来的是123456
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGN)).build();
        return build.verify(token);
    }

   /* public static void main(String[] args) {
        DecodedJWT verify = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MTcxMDg1MDAsInVzZXJuYW1lIjoiYWRtaW4ifQ.geBEtpluViRUg66_P7ZisN3I_d4e32Wms8mFoBYM5f0");
        System.out.println(verify.getClaim("password").asString());
    }*/
}
